package com.trade.module.base.service.impl;

import com.trade.module.base.entity.Department;
import com.trade.module.base.repository.DepartmentRepository;
import com.trade.module.base.service.DepartmentService;
import com.trade.common.utils.*;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;

/**
 * Class Description:
 *
 * @Version v1.0 2017/5/1 17:38
 * @JDK version 1.8.0_51
 * @Author zfb
 */
@Log4j
@Service
@Transactional
public class DepartmentServiceImpl implements DepartmentService{

    @Autowired
    private DepartmentRepository deptRepository;

    /**
     * 自动生成部门级别及编码
     *
     * 编码规则：
     * 1.	组织编码(org001000000)  ---1
     * 2.	部门编码(org001001000)  ---2
     * 3.	科室编码(org001001001)  ---3
     */
    public boolean getDepartmentCode(Department department) {
        if(XaUtil.isEmpty(department)){
            log.debug("生成系统菜单编码和菜单级别失败，资源信息为" + department);
            return false;
        }
        boolean result = false;
        String pId = department.getParentDeptId();
        if(XaUtil.isNotEmpty(pId)){
            log.debug("开始生成住址机构编码和级别，上级菜单ID为： " + pId);
            List<SearchFilter> filters = SearchFilter.parse(null);//解析查询条件,自动添加数据状态过滤
            SearchFilter parentIdFilter = new SearchFilter("id", SearchFilter.Operator.EQ, pId);
            filters.add(parentIdFilter);
            Department dept = deptRepository.findOne(DynamicSpecifications.bySearchFilter(filters, Department.class));

            if(dept!=null){
                String pElementCode = dept.getElementCode();
                //查找当前父节点下子节点信息
                List<Department> deptNodeList = deptRepository.findByParentDeptId(pId);
                int childrenCount = XaUtil.isNotEmpty(deptNodeList) ? (deptNodeList.size() + 1) : 1;
                //根据父级部门编码设置当前资源的级别、编码
                String plevel = dept.getDeptLevel();
                if(Constants.DEPARTMENT_LEVEL_ORG.equals(plevel)){
                    department.setDeptLevel(Constants.DEPARTMENT_LEVEL_DEPT);
                    department.setElementCode(pElementCode.substring(0, 6) + String.format("%03d", childrenCount) + "000");
                    result = true;
                }else if(Constants.DEPARTMENT_LEVEL_DEPT.equals(plevel)){
                    department.setDeptLevel(Constants.DEPARTMENT_LEVEL_GROUP);
                    department.setElementCode(pElementCode.substring(0, 9) + String.format("%03d", childrenCount));
                    result = true;
                }else{
                    result = false;
                    log.error("生成部门编码和部门级别失败，上级部门级别定义不正确，上级部门ID=" + dept.getId());
                }
            } else {
                List<Department> deptNodelist = deptRepository.findByDeptLevel(Constants.DEPARTMENT_LEVEL_ORG);
                department.setDeptLevel(Constants.DEPARTMENT_LEVEL_ORG);
                int deptSize = 1;
                if(deptNodelist!=null && deptNodelist.size()>0){
                    deptSize += deptNodelist.size();
                }
                department.setElementCode("org"+String.format("%03d",deptSize)+"000000");
                result = true;
            }

        }else{
            log.debug("不存在根节点组织机构！");
            List<Department> deptNodelist = deptRepository.findByDeptLevel(Constants.DEPARTMENT_LEVEL_ORG);
            department.setDeptLevel(Constants.DEPARTMENT_LEVEL_ORG);
            int deptSize = 1;
            if(deptNodelist!=null && deptNodelist.size()>0){
                deptSize += deptNodelist.size();
            }
            department.setElementCode("org"+String.format("%03d",deptSize)+"000000");
            result = true;
        }
        return result;
    }

    /**
     * 新增
     *
     * @param department 部门对象
     * @return department 部门对象
     */
    @Override
    @Transactional
    public Department save(Department department) {
        boolean setCodeResult = getDepartmentCode(department);
        Department deptPo = null;
        if(setCodeResult){
            List<SearchFilter> filters = SearchFilter.parse(null);
            SearchFilter flagFilter = filters.get(0);
            SearchFilter deptNameFilter = new SearchFilter("deptName", SearchFilter.Operator.EQ, department.getDeptName());
            SearchFilter deptLevelFilter = new SearchFilter("deptLevel", SearchFilter.Operator.EQ, department.getDeptLevel());
            SearchFilter parentDeptIdFilter = new SearchFilter("parentDeptId", SearchFilter.Operator.EQ, department.getParentDeptId());
            filters.add(deptNameFilter);
            filters.add(deptLevelFilter);
            filters.add(parentDeptIdFilter);
            List<Department> exists = deptRepository.findAll(DynamicSpecifications.bySearchFilter(filters, Department.class));
            if(null == exists || exists.size() == 0){
                flagFilter.value = Constants.DATA_FLAG_DELETE;
                exists = deptRepository.findAll(DynamicSpecifications.bySearchFilter(filters, Department.class));
                if(null != exists && exists.size() > 0){
                    Department exist =null;
                    try {
                        exist = exists.get(0);
                        BeanUtil.copyAllProperties(department, exist);
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("复制机构实体异常！"+ exist);
                        return null;
                    }
                    exist.setDataFlag(Constants.DATA_FLAG_OK);
                    deptPo = deptRepository.save(exist);
                    log.debug("更新组织机构数据删除状态！" + exist);
                }else{
                    deptPo = deptRepository.save(department);
                }
            }else{
                log.warn("该组织机构已经存在！" + department);
            }
        }
        return deptPo;
    }
}

